#include <stdio.h>
#include <string.h>

#define MAX_LEN 128

void process_line(const char *str)
{
    char buf[MAX_LEN] = { 0 };
    int i, x, y;

    if (strncasecmp(str, "PRINT", strlen("print")) == 0) {
        sscanf(str, "PRINT %[a-zA-Z ,]", buf);
        printf(">> %s\n", buf);
    } else if(strncasecmp(str, "LOOP", strlen("LOOP")) == 0) {
        sscanf(str, "LOOP %d %[a-zA-Z ,]", &x, buf);
        printf(">> loop %d times:\n", x);
        for (i=0; i<x; i++) {
            printf("  >> %d %s\n", i, buf);
        }
    } else if (strncasecmp(str, "ADD", strlen("ADD")) == 0) {
        sscanf(str, "ADD %d %d", &x, &y);
        printf(">> %d + %d = %d\n", x, y, x+y);
    } else if (strncasecmp(str, "SUB", strlen("SUB")) == 0) {
        sscanf(str, "SUB %d %d", &x, &y);
        printf(">> %d - %d = %d\n", x, y, x-y);
    } else if (str[0] == '#'){
        /* comment line, do nothing */
    } else {
        printf(">> wrong line: %s\n", str);
    }
}


int main(int argc, char *argv[])
{
    int i = 0;
    FILE *file;
    char buf[MAX_LEN] = { 0 };

    if (argc != 2) {
        printf("wrong args number\n");
    }
    
    file = fopen(argv[1], "r");
    if (!file) {
        printf("open %s error\n", argv[1]);
        return 1;
    }

    while (fgets(buf, MAX_LEN, file) != NULL) {
        process_line(buf);
    }

    fclose(file);
    
    return 0;
}
